package org.petstore.web.servlet;

import org.petstore.domain.*;
import org.petstore.service.CartService;
import org.petstore.service.CatalogService;
import org.petstore.service.LogService;
import org.petstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ViewOrderServlet extends HttpServlet {
    private static final String VIEWORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private Order order;
    private Account account;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String Id= request.getParameter("orderId");
        int orderId=0;
        order=null;
        try {
            orderId= Integer.parseInt(Id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        OrderService orderService=new OrderService();
        if(orderId!=0){
            order=orderService.getOrder(orderId);
            System.out.println("exist");
        }
        if(order!=null){
            session.setAttribute("order", order);
            account = (Account) session.getAttribute("account");
            if(account != null){
                HttpServletRequest httpRequest= request;
                String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " 查看订单 " + order;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            request.getRequestDispatcher(VIEWORDER).forward(request, response);
        }
        else {
            session.setAttribute("message", "An error occurred processing your order (order was null).");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }
    }
}
